package auth

import (
	"github.com/gin-gonic/gin"

	v1 "github.com/runningwater/gohub/app/http/controllers/api/v1"
	"github.com/runningwater/gohub/app/requests"
	"github.com/runningwater/gohub/pkg/captcha"
	"github.com/runningwater/gohub/pkg/logger"
	"github.com/runningwater/gohub/pkg/response"
	"github.com/runningwater/gohub/pkg/verifycode"
)

type VerifyCodeController struct {
	v1.BaseApiController
}

// ShowCaptcha 显示图片验证码
func (vc *VerifyCodeController) ShowCaptcha(c *gin.Context) {
	// 生成验证码
	id, b64s, answer, err := captcha.NewCaptcha().GenerateCaptcha()
	logger.LogIf(err)
	logger.DebugString("captchaController", "captcha id: ", id)
	logger.DebugString("captchaController", "captcha answer: ", answer)
	response.JSON(c, gin.H{
		"captcha_id":    id,
		"captcha_image": b64s,
	})
}

// SendUsingPhone 发送手机验证码
func (vc *VerifyCodeController) SendUsingPhone(c *gin.Context) {

	// 1. 验证表单
	request := requests.VerifyCodeRequest{}
	if ok := requests.Validate(c, &request, requests.VerifyCodePhone); !ok {
		return
	}

	// 2. 发送手机验证码
	if ok := verifycode.NewVerifyCode().SendSMS(request.Phone); !ok {
		response.Abort500(c, "发送短信失败~~")
	} else {
		response.Success(c)
	}

	response.Success(c)
}

// SendUsingEmail 发送邮箱验证码
func (vc *VerifyCodeController) SendUsingEmail(c *gin.Context) {
	// 1. 验证表单
	request := requests.VerifyCodeEmailRequest{}
	if ok := requests.Validate(c, &request, requests.VerifyCodeEmail); !ok {
		return
	}

	// 2. 发送邮箱验证码
	if err := verifycode.NewVerifyCode().SendEmail(request.Email); err != nil {
		response.Abort500(c, "发送邮件失败~~")
	} else {
		response.Success(c)
	}
}
